<template>
  <div class="oe-exam-manage" v-loading="loading">
    <top-tip v-if="!this.stepMode && batchTitle" :title="titleListTop" :batchTitle="batchTitle" :examTitle="examTitle"></top-tip>
    <div class="oe-exam-content">
      <div class="oe-manage-search">
        <span class="oe-manage-text">考场名称：</span>
        <span class="oe-manage-input">
          <a-input placeholder="输入考场名称" v-model="key" @keyup.13="getExamList" />
        </span>
        <span class="oe-manage-btns">
          <a-button type="primary" @click.stop="getExamList">查询</a-button>
          <a-button type="primary" @click.stop="add('新增')"  v-if="operationList.includes('add/edit/del:room')">导入考场</a-button>
          <a-button type="primary" @click.stop="onTimesOpen('新增')"  v-if="operationList.includes('add/edit/del:room')">设置轮次</a-button>
          <a-button type="primary" @click.stop="setTeacher()"  v-if="operationList.includes('add/edit/del:room')">设置监考教师</a-button>
          <a-button type="primary"  v-if="operationList.includes('add/edit/del:room')">
            <a :href="exportUrl">导出考场信息</a>
          </a-button>
        </span>
      </div>
      <div class="oe-exam-container">
        <a-table
          class="room-table"
          :columns="columns"
          :dataSource="dataList"
          :pagination="pagination"
          @change="onTableChange1"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <span slot="action" slot-scope="text, record">
            <a-tooltip placement="bottom" title="考生信息">
              <span
                @click="getStuList(record)"
                v-if="operationList.includes('add/edit/del:room')"
                class="action-icon click-pointer"
              >
                <i class="iconfont icon-xueshengguanli"></i>
              </span>
            </a-tooltip>
            <a-tooltip placement="bottom" title="轮次编辑">
              <span
                @click="onTimesOpen('编辑',record.Id)"
                 v-if="operationList.includes('add/edit/del:room')"
                class="action-icon click-pointer"
              >
                <i class="iconfont icon-edit"></i>
              </span>
            </a-tooltip>
            <a-tooltip placement="bottom" title="下载客户端">
              <span
                @click="download(record)"
                 v-if="operationList.includes('add/edit/del:room')"
                class="action-icon click-pointer"
              >
                <i class="iconfont icon-xiazai"></i>
              </span>
            </a-tooltip>
            <a-tooltip placement="bottom" title="删除">
              <span
                @click="del(record)"
                 v-if="operationList.includes('add/edit/del:room')"
                class="action-icon click-pointer"
              >
                <i class="iconfont icon-delete"></i>
              </span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>
    <a-modal
      title="设置轮次"
      class="oe-studentAdd"
      :visible="timesVisible"
      @cancel="onTimesCancel"
      width="550px"
    >
      <template v-for="(examtime, index) in moretime">
        <div :key="index" class="oe-other-set__item" style="margin-top:10px">
          <span class="oe-let-time__title">轮次{{ index + 1 }}：</span>
          <a-date-picker
            :ref="'startTime_' + index"
            :disabled-date="disabledNormalStartDate"
            :show-time="{ defaultValue: $moment('00:00:00', 'HH:mm:ss') }"
            format="YYYY-MM-DD HH:mm"
            v-model="examtime.starttime"
            placeholder="请选择时间"
            @change="changetime"
            @openChange="handleStartNormalOpenChange($event, examtime)"
          />
          <span class="oe-let-time__split">--</span>
          <a-date-picker
            :ref="'endTime_' + index"
            :disabled-date="disabledNormalEndDate"
            :show-time="{ defaultValue: $moment('00:00:00', 'HH:mm:ss') }"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择时间"
            v-model="examtime.endtime"
            :open="examtime.endOpen"
            @change="changetime"
            @openChange="handleEndNormalOpenChange($event, examtime)"
          />
          <i
            @click="deletetime(index)"
            class="iconfont icon-delete"
            style="margin-left: 10px;font-size: 18px;"
          ></i>
        </div>
      </template>
      <template slot="footer">
        <a-button @click="addtimes" type="primary" html-type="submit">添加轮次</a-button>
        <a-button @click="savetimes" type="primary" html-type="submit">确定</a-button>
        <a-button @click.stop="onTimesCancel">取消</a-button>
      </template>
    </a-modal>
    <a-modal
      title="考生信息"
      width="65%"
      class="oe-exam-table-modal"
      centered
      v-model="tableVisible"
      :afterClose="clearData"
    >
      <div class="oe-exam-table-input">
        <span class="oe-question-text">轮次：</span>
        <span class="oe-manage-select">
          <a-select
            v-model="roundId"
            @change="getRoundId"
            showSearch
            :allowClear="true"
            optionFilterProp="children"
            placeholder="请选择轮次"
            style="width: 26%"
          >
            <a-select-option
              v-for="(item, index) in roundList"
              :value="item.Id"
              :index="index"
              :key="item.Id"
            >
              {{
              item.StartTime
              }}-
              {{
              item.EndTime
              }}
            </a-select-option>
          </a-select>
        </span>
        &nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;
        姓名/学号/用户名:
        <a-input v-model="searchExam" placeholder="学生姓名/学号/用户名" @keyup.13="getCarryList"></a-input>
        <!-- 考试类型：<a-select v-model="tableSelect" style="width: 120px">
          <a-select-option value="0">正式考</a-select-option>
          <a-select-option value="1">补考</a-select-option>
        </a-select>&nbsp;&nbsp;&nbsp; -->
        <a-button type="primary" @click="getCarryList">查询</a-button>
        <a-button type="primary">
          <a :href="exportStuUrl">导出考生</a>
        </a-button>
      </div>
      <div class="oe-exam-table-table">
        <a-table
          :columns="columns1"
          :dataSource="data1List"
          :pagination="paginationObj"
          @change="onTableChange"
          :rowSelection="rowSelection"
          :scroll="{ y: 400 }"
        ></a-table>
      </div>
      <div slot="footer" style="display: none;">
        <!-- <a-button type="primary" @click="sureCarry">确认</a-button>
        <a-button @click.stop="tableVisible = false">取消</a-button>-->
      </div>
    </a-modal>
    <a-modal
      title="客户端"
      class="oe-student"
      :visible="cancelPublish"
      width="500px"
      :closable="false"
    >
      <div class="oe-select">
        <span class="oe-manage-select">
          <h3>温馨提示：</h3>
          <div>1、线下考试取消发布后，需要重新分配座位号</div>
          <div>2、已经有作答学生的考试不允许取消发布</div>
          <div>3、取消发布后，学生将不能看到该考试</div>
        </span>
      </div>
      <div class="oe-manage-search">
        <span class="oe-manage-text">下载客户端名称：</span>
        <span class="oe-manage-input">
          <a-input placeholder="输入考场名称" v-model="clientName" style="width: 300px;" />
          <a-tooltip placement="bottom" class="oe-push-top__title">
            <template slot="title">
              <span class="oe-title-info">该名称为下载客户端时候的名称，客户端名称不能输入中文和特殊符号，否则可能会导致无法打开</span>
            </template>
            <i class="iconfont icon-wenti"></i>
          </a-tooltip>
        </span>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="downClient(0)" style="margin-top: 16px">下载正式考客户端</a-button>
        <!-- <a-button type="primary" @click="downClient(1)" style="margin-top: 16px">下载补考客户端</a-button> -->
        <a-button @click.stop="cancelPublish = false">取消</a-button>
      </template>
    </a-modal>
    <a-modal
      title="监考教师"
      class="oe-student"
      :visible="cancelTeacher"
      width="500px"
      :closable="false"
    >
      <div class="oe-select">
        <span class="oe-manage-select">
          <h3>温馨提示：</h3>
          <div>1、该监考教师的账号为登录客户端时使用</div>
          <div>2、下载客户端之前必须要设置监考教师</div>
        </span>
      </div>
      <div class="oe-list-line">
        <span class="oe-title-text">监考教师：</span>
        <a-select
          v-model="inspectionId"
          style="width:300px"
          showSearch
          @change="ChangeTea"
          :allowClear="true"
          optionFilterProp="children"
          placeholder="请选择监考教师"
        >
          <a-select-option
            v-for="item in teacherList"
            :value="item.id"
            :key="item.id"
            with="100%"
          >{{ item.text }}</a-select-option>
        </a-select>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="saveTeacher()" style="margin-top: 16px">确定</a-button>
        <a-button @click.stop="cancelTeacher = false">取消</a-button>
      </template>
    </a-modal>
    <a-modal v-model="visibleQuesName" title="导入考场" width="926px" wrapClassName="oe-modal__manage">
      <div class="oe-modal-one">
        <span class="oe-modal-input">
          <a-input placeholder="请输入考场名称" v-model="roomTitle" @keyup.13="getWorkQuestion"></a-input>
        </span>
        <a-button class="oe-btn-right" type="primary" @click="getWorkQuestion">查询</a-button>
      </div>
      <div class="oe-modal-table">
        <a-table
          :rowSelection="{ selectedRowKeys: selectedStudent, onChange: onSelectStudent }"
          :columns="modalColumns"
          :dataSource="modalList"
          :pagination="modalPagination"
          :scroll="{ y: 470 }"
          @change="onModalChange"
        />
      </div>
      <template slot="footer">
        <a-button type="primary" @click.stop="saveedit">确定</a-button>
        <a-button class="oe-btn-delete" @click.stop="visibleQuesName = false">取消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  name: 'examManage',
  mixins: [GetOperationList],
  components: {
    topTip
  },
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
      titleListTop: [{ text: '批次(考试)管理' }, { text: '考场管理', color: '#1890ff' }],
      roundId: undefined,
      roundList: [],
      exportStuUrl: '',
      cancelTeacher: false,
      inspectionId: undefined,
      teacherList: [],
      // 分页配置
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          // this.getExamList(current, pageSize);
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          // console.log(props);
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      loading: false,
      texttitle: '新增考场',
      isShowModel: false,
      key: '',
      // 考试名称
      searchExam: '',
      tableSelect: '正式考',
      // 表标题
      columns: [
        {
          title: '序号',
          dataIndex: 'Number',
          width: '8%',
          key: 'Number',
          align: 'center'
        },
        {
          title: '考场名称',
          dataIndex: 'Name',
          width: '10%',
          key: 'Name',
          sorter: true,
          align: 'center'
        },
        {
          title: '监考教师姓名',
          dataIndex: 'DisplayName',
          width: '10%',
          key: 'DisplayName',
          sorter: true,
          align: 'center'
        },
        {
          title: '监考教师用户名',
          dataIndex: 'UserName',
          width: '10%',
          key: 'UserName',
          sorter: true,
          align: 'center'
        },
        {
          title: '机位数',
          dataIndex: 'ComputerNumber',
          width: '12%',
          key: 'ComputerNumber',
          sorter: true,
          align: 'center'
        },
        {
          title: '备用机位数',
          dataIndex: 'BackupComputerNumber',
          width: '10%',
          key: 'BackupComputerNumber',
          sorter: true,
          align: 'center'
        },
        {
          title: '考场地址',
          dataIndex: 'Address',
          width: '15%',
          key: 'Address',
          sorter: true,
          align: 'center'
        },
        {
          title: '创建时间',
          dataIndex: 'DateCreated',
          width: '13%',
          key: 'DateCreated',
          sorter: true,
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          width: '13%',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      // 数据列表
      dataList: [],
      cancelPublish: false,
      // 操作List
      operationList: [],
      roomId: '',
      // 、操作list
      form: {
        RoomName: '',
        ComputerNumber: '',
        Address: '',
        BackupComputerNumber: ''
      },
      rules: {
        RoomName: [{ required: true, message: '请输入考场名称', trigger: 'blur' }],
        Address: [{ required: true, message: '请输入考场地址', trigger: 'blur' }],
        ComputerNumber: [{ required: true, message: '请输入考场机位数', trigger: 'blur' }],
        BackupComputerNumber: [{ required: true, message: '请输入考场备用机位', trigger: 'blur' }]
      },
      clientName: 'client',
      IsOpList: [],
      exportUrl: '',
      tableVisible: false,
      // 表标题
      columns1: [
        {
          title: '序号',
          dataIndex: 'Number',
          width: '10%',
          key: 'Number'
        },
        {
          title: '姓名',
          dataIndex: 'DisplayName',
          width: '15%',
          key: 'DisplayName',
          sorter: true
        },
        {
          title: '学号',
          dataIndex: 'UserNo',
          width: '15%',
          key: 'UserNo',
          sorter: true
        },
        {
          title: '用户名',
          dataIndex: 'UserName',
          width: '17%',
          key: 'UserName',
          sorter: true
        },
        {
          title: '座位号',
          dataIndex: 'SeatNumber',
          width: '13%',
          key: 'SeatNumber',
          sorter: true
        },
        {
          title: '开始时间',
          dataIndex: 'StartTime',
          width: '15%',
          key: 'StartTime',
          sorter: true
        },
        {
          title: '结束时间',
          dataIndex: 'EndTime',
          width: '15%',
          key: 'EndTime',
          sorter: true
        }
      ],
      // 数据列表
      data1List: [],
      // 分页配置
      paginationObj: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.paginationObj.current = current;
          this.paginationObj.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          // this.getExamList(current, pageSize);
          this.paginationObj.current = current;
          this.paginationObj.pageSize = pageSize;
        },
        buildOptionText(props) {
          // console.log(props);
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      examRoomId: '',
      modalPagination: {
        pageSizeOptions: ['10', '20', '40', '80', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.modalPagination.current = current;
          this.modalPagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0
      },
      modalColumns: [
        {
          title: '序号',
          dataIndex: 'number',
          width: '8%',
          key: 'number'
        },
        {
          title: '考场名称',
          dataIndex: 'Name',
          width: '15%',
          key: 'Name',
          sorter: true
        },
        {
          title: '机位数',
          dataIndex: 'ComputerNumber',
          width: '12%',
          key: 'ComputerNumber',
          sorter: true
        },
        {
          title: '备用机位数',
          dataIndex: 'BackupComputerNumber',
          width: '15%',
          key: 'BackupComputerNumber',
          sorter: true
        },
        {
          title: '考场地址',
          dataIndex: 'Address',
          width: '50%',
          key: 'Address',
          sorter: true
        }
      ],
      modalList: [],
      visibleQuesName: false,
      roomTitle: '',
      selectedRowKeys: [],
      selectedStudent: [],
      selectedRows: [],
      timesVisible: false,
      moretime: [
        {
          endtime: null,
          starttime: null,
          endOpen: false,
          idx: 0,
          name: '轮次1'
        }
      ],
      idx: 0,
      cacheItem: '',
      maxtime: '',
      startNormalValue: null,
      endNormalValue: null,
      examTitle:'',
      batchTitle:'',
    };
  },
  mounted() {
    this.getExamOperation();
  },
  props: {
    examid: {
      type: String,
      default: ''
    },
    batchid: {
      type: String,
      default: ''
    },
    stepMode:{
      type:Boolean,
      default:false
    }
  },
  methods: {
    handleStartNormalOpenChange(open, data) {
      this.cacheItem = data;
      if (!open) {
        let index = this.moretime.findIndex((item) => {
          return item.idx === data.idx;
        });
        if (index > -1) {
          this.moretime[index].endOpen = true;
        }
      }
    },
    handleEndNormalOpenChange(open, data) {
      let index = this.moretime.findIndex((item) => {
        return item.idx === data.idx;
      });
      if (index > -1) {
        this.moretime[index].endOpen = open;
      }
    },
    changetime(val) {
      this.maxtime = this.$moment(this.endNormalValue).diff(this.$moment(this.startNormalValue), 'minute');
    },
    disabledNormalStartDate(startNormalValue) {
      let index = this.moretime.findIndex((item) => {
        return item.idx === this.cacheItem.idx;
      });
      if (index > -1) {
        if (this.cacheItem.idx) {
          const otherendTime = this.moretime[index - 1].endtime;
          if (!startNormalValue || !otherendTime) {
            return false;
          }
          return startNormalValue.valueOf() <= this.moretime[index - 1].endtime.valueOf();
        } else {
          const endNormalValue = this.moretime[index].endtime;
          if (!startNormalValue || !endNormalValue) {
            return false;
          }
          return startNormalValue.valueOf() > endNormalValue.valueOf();
        }
      }
    },
    disabledNormalEndDate(endNormalValue) {
      let index = this.moretime.findIndex((item) => {
        return item.idx === this.cacheItem.idx;
      });
      if (index > -1) {
        const startNormalValue = this.moretime[index].starttime;
        if (!endNormalValue || !startNormalValue) {
          return false;
        }
        return startNormalValue.valueOf() >= endNormalValue.valueOf();
      }
    },
    savetimes() {
      for (let i = 0; i < this.moretime.length; i++) {
        if (this.moretime[i].starttime === null || this.moretime[i].endtime === null) {
          return this.$message.warn('请输入轮次时间');
        }
        // if (this.moretime[i].starttime.valueOf() < this.batchstarttime || this.moretime[i].endtime.valueOf() > this.batchendtime) {
        //   return this.$message.warn('轮次时间需在批次时间之内');
        // }
      }
      let roomIds = [];
      if (this.roomId === '') {
        roomIds = this.selectedRowKeys
      } else {
        roomIds = [this.roomId];
      }
      let params = {
        examRoomIds: roomIds,
        times: this.moretime.map(
          (item) =>
            `${this.$moment(item.starttime).format('YYYY-MM-DD HH:mm:ss')};${this.$moment(item.endtime).format(
              'YYYY-MM-DD HH:mm:ss'
            )}`
        ),
        examId: this.examid
      };
      this.loading = true;
      this.$http.post('/api/design/examRoom/saveRoomTime', params).then((rst) => {
        this.loading = false;
        if (rst.code === 1) {
          this.roomId = '';
          this.onTimesCancel();
          this.$message.success(rst.msg);
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    addtimes() {
      if (this.moretime[this.idx].endtime != null && this.moretime[this.idx].starttime != null) {
        this.moretime.push({
          endtime: null,
          starttime: null,
          endOpen: false,
          idx: (this.idx += 1)
        });
      } else {
        this.$message.warn('请将前一个时间点选择完成');
      }
    },
    deletetime(index) {
      if (this.moretime.length > 1) {
        this.moretime.splice(index, 1);
        this.moretime.forEach((item, i) => {
          if (i >= index) {
            item.idx -= 1;
          }
        });
        this.idx -= 1;
      } else {
        this.$message.warn('至少需要一个考试时间');
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    onTimesOpen(type, roomId) {
      if (type === '新增') {
        if (this.selectedRowKeys.length > 0) {
          this.timesVisible = true;
        } else {
          this.$message.warn('请至少选择一个考场');
        }
      } else if (type === '编辑') {
        this.loading = true;
        this.$http
          .post('/api/design/examRoom/getExamTime', {
            examRoomId: roomId
          })
          .then((res) => {
            this.loading = false;
            if (res.code == 1) {
              if (res.list.length > 0) {
                this.roomId = roomId;
                this.timesVisible = true;
                this.moretime = [];
                res.list.forEach((item, index) => {
                  this.moretime.push({
                    endtime: this.$moment(item.EndTime, 'YYYY-MM-DD HH:mm:ss'),
                    starttime: this.$moment(item.StartTime, 'YYYY-MM-DD HH:mm:ss'),
                    endOpen: false,
                    idx: index
                  });
                });
                this.idx = res.list.length - 1;
              } else {
                this.roomId = roomId;
                this.timesVisible = true;
                //this.$message.warn('该考场无轮次，请先新增');
              }
            }
          });
      }
    },
    onTimesCancel() {
      this.selectedRowKeys = [];
      this.timesVisible = false;
      this.moretime = [
        {
          endtime: null,
          starttime: null,
          endOpen: false,
          idx: 0,
          name: '轮次1'
        }
      ];
      this.idx = 0;
      this.cacheItem = '';
      this.maxtime = '';
      this.roomId = '';
      this.startNormalValue = null;
      this.endNormalValue = null;
    },
    clearData() {
      this.tableSelect = '正式卷';
      this.searchExam = '';
      this.roundId = undefined;
    },
    // 判断是否是只读
    getIsWrite(type) {
      type = "add/edit/del:room";
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 获取页面操作
    getExamOperation() {
      console.log(11111);
      this.exportUrl =
        '/api/design/examroom/getExamRoomList?examId=' + this.examid + '&batchId=' + this.batchid + '&export=1';
      this.loading = true;
      this.GetOperationList('examId',this.examid,'roomManagement').then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code == 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if(item.IsWrite){
              this.operationList.push(item.Name);
              }
            });
            this.IsOpList = rst.list;
            // this.operationList = rst.list;
          }
          this.getExamList();
          this.examTitle = rst.examTitle
          this.batchTitle = rst.batchTitle
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    // 获取考试列表
    getExamList(sort) {
      this.loading = true;
      this.$http
        .post('/api/design/examroom/getExamRoomList', {
          title: this.examName,
          batchId: this.batchid,
          examId: this.examid,
          pageSize: this.pagination.pageSize || 10,
          page: this.pagination.current || 1,
          key: this.key,
          sort
        })
        .then((rst) => {
          this.loading = false;
          this.dataList = [];
          if (rst.code == 1) {
            this.pagination.current = rst.pagination.pageIndex;
            this.pagination.pageSize = rst.pagination.pageSize;
            this.pagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((exam, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.dataList.push({
                  ...exam,
                  key:exam.Id,
                  Number: number
                });
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    //编辑保存
    saveedit() {
      this.loading = true;
      this.$http
        .post('/api/design/examRoom/saveExamRoom', {
          examId: this.examid,
          roomIds: this.selectedStudent
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code === 1) {
            this.selectedStudent = [];
            this.visibleQuesName = false;
            this.getExamList();
            this.stepMode && this.$parent.getExamStatus(2)
            this.$message.success(rst.msg);
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    // 按照条件查询
    searchList() {
      this.getExamList();
    },
    del(data) {
      if (!this.getIsWrite('删除')) {
        return;
      }
      this.$confirm({
        title: '提示',
        content: '你确定要删除该考场吗？',
        centered: true,
        onOk: () => {
          this.$http
            .post('/api/design/examroom/deleteExamRoom', {
              id: data.Id,
              examId: this.examid,
              batchid: this.batchid
            })
            .then((rst) => {
              if (rst.code === 1) {
                this.$message.success(rst.msg);
                this.stepMode && this.$parent.getExamStatus(2)
                this.getExamList();
              } else {
                this.$message.error(rst.msg);
              }
            });
        },
        onCancel() {}
      });
    },
    add(type, data) {
      if (type == '新增') {
        if (!this.getIsWrite('新增')) {
          return;
        }
        this.selectedStudent = [];
        this.getWorkQuestion();
      }
    },
    // 点击table排序
    onModalChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getWorkQuestion(pagenation.current, pagenation.pageSize, sortOrder);
    },
    onSelectStudent(selectedRowKeys, selectedRows) {
      this.selectedStudent = selectedRowKeys;
    },
    getWorkQuestion(current, pageSize, sort, type) {
      this.loading = true;
      this.$http
        .post('/api/design/examRoom/getRoomList', {
          examId: this.examid,
          sort,
          pageSize: pageSize || 10,
          page: current || 1,
          title: this.roomTitle
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code === 1) {
            this.visibleQuesName = true;
            this.modalList = [];
            this.modalPagination.current = rst.pagination.pageIndex;
            this.modalPagination.pageSize = rst.pagination.pageSize;
            this.modalPagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                let key = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index;
                this.modalList.push({
                  ...item,
                  key: item.Id,
                  number: number
                });
              });
            }
            if (type) {
              let index = this.schoolList.findIndex((item) => {
                return item.id === rst.schoolId;
              });
              if (index > -1) {
                this.school = this.schoolList[index].id;
              }
              // this.getFactoryList('', rst.schoolId);
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    download(data) {
      this.cancelPublish = true;
      this.examRoomId = data.Id;
      this.clientName = data.ClientName;
      return;
    },
    downClient(type) {
      if (!this.clientName) {
        this.$message.error('请输入客户端名称');
        return;
      }
      this.$http
        .post('/api/design/examRoom/checkClient', {
          examId: this.examid,
          examRoomId: this.examRoomId,
          examType: type,
          title: this.clientName
        })
        .then((rst) => {
          if (rst.code === 1) {
            this.$message.success('正在下载中，请稍后..');
            let clientRepairUrl = '/downloadClient/examroom/downloadDegreeClient?resId=' + rst.resId;
            // this.examid +
            // '&examRoomId=' +
            // this.examRoomId +
            // '&examType=' +
            // type;
            //this.clientNowUrl = '/api/design/examroom/downloadDegreeClient?examId=' + this.examid + '&examRoomId='+data.Id+'&examType=0';
            window.open(clientRepairUrl, '_self');
            this.cancelPublish = false;
          } else {
            this.$message.error(rst.msg);
            return;
          }
        });
    },
    // 点击table排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getCarryList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    onTableChange1(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getExamList(sortOrder);
    },
    getStuList(data) {
      this.examRoomId = data.Id;
      this.getCarryList();
    },
    getCarryList(current, pageSize, sorter) {
      let thisRoundId = '';
      if (!this.roundId) {
        thisRoundId = this.roundId;
      }
      this.exportStuUrl =
        '/api/design/examroom/getRoomStuList?export=1&examId=' +
        this.examid +
        '&key=' +
        this.searchExam +
        '&examType=' +
        this.tableSelect +
        '&examRoomId=' +
        this.examRoomId +
        '&roundId=' +
        thisRoundId;
      this.loading = true;
      this.$http
        .post('/api/design/examRoom/getRoomStuList', {
          key: this.searchExam,
          examType: this.tableSelect,
          examRoomId: this.examRoomId,
          roundId: this.roundId,
          examId: this.examid,
          sort: sorter ? sorter : '',
          pageSize: pageSize ? pageSize : 10,
          page: current ? current : 1
        })
        .then((rst) => {
          this.loading = false;
          this.data1List = [];
          if (rst.code === 1) {
            this.paginationObj.current = rst.pagination.pageIndex;
            this.paginationObj.pageSize = rst.pagination.pageSize;
            this.paginationObj.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let time = item.StartTime + '--' + item.EndTime;
                let Number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.data1List.push({
                  ...item,
                  time,
                  Number
                });
              });
            }
            // this.dataList = rst.list;
            if (!this.tableVisible) {
              this.getRoundList(this.examRoomId);
              this.tableVisible = true;
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    getRoundList(examRoomId) {
      this.$http
        .post('/api/design/examroom/getExamTime', {
          examRoomId: examRoomId
        })
        .then((rst) => {
          this.roundList = rst.list;
        });
    },
    getRoundId(value) {
      this.roundId = value;
    },
    ChangeTea(value) {
      this.inspectionId = value;
    },
    //获取责任教师
    setTeacher(val) {
      if (this.selectedRowKeys.length == 0) {
        this.$message.warn('请至少选择一个考场');
        return;
      }
      this.fetching = true;
      this.$http
        .post('/api/design/workexam/getDutyTea', {
          q: val ? val : ''
        })
        .then((rst) => {
          this.fetching = false;
          this.teacherList = [];
          if (rst.code == 1) {
            this.teacherList = rst.list;
            this.cancelTeacher = true;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    saveTeacher() {
      let roomIds = [];
      if (this.roomId === '') {
        roomIds = this.selectedRowKeys
      } else {
        roomIds = [this.roomId];
      }
      this.$http
        .post('/api/design/examRoom/setTeacher', {
          examRoomIds: roomIds,
          teacherId: this.inspectionId,
          examId: this.examid
        })
        .then((rst) => {
          if (rst.code == 1) {
            this.roomId = '';
            this.inspectionId = undefined;
            this.getExamList();
            this.cancelTeacher = false;
            this.selectedRowKeys = [];
          } else {
            this.$message.error(rst.msg);
          }
        });
    }
  }
};
</script>
